package com.jml.builder;


import com.jml.session.Configuration;
import com.jml.session.DataSource;
import com.jml.utils.ClassUtil;
import com.jml.utils.PropertiesUtil;
import java.util.List;


public class XMLConfigBuilder extends BaseBuilder {
    private PropertiesUtil propertiesUtil;

    public XMLConfigBuilder() {
    }

    public XMLConfigBuilder(String properiesName) {
        this.configuration = new Configuration();
        this.propertiesUtil = new PropertiesUtil(properiesName);
    }

    /**
     * 解析配置文件mybatis-config-xml
     */
    public Configuration parse() {
        // 1.解析配置文件获取DataSource
        propertieDataSource();
        // 2.解析mappers注册
        propertieMappers();
        return this.configuration;
    }

    private void propertieDataSource() {
        String driver = propertiesUtil.readProperty("driver");
        String url = propertiesUtil.readProperty("url");
        String username = propertiesUtil.readProperty("username");
        String password = propertiesUtil.readProperty("password");
        DataSource dataSource = new DataSource(driver, url, username, password);
        this.configuration.setDataSource(dataSource);
    }

    private void propertieMappers() {
        String mappers = propertiesUtil.readProperty("mappers");
        this.configuration.setMappers(mappers);
        // 使用java的反射机制获取该包下面 所有的 mapper接口
        List<Class<?>> classesByPackageName = ClassUtil.getClassSet(mappers);
        for (int i = 0; i < classesByPackageName.size(); i++) {
            Class classInfo = classesByPackageName.get(i);
            this.configuration.addMapper(classInfo);
        }
    }

}
